﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SQLite;
using WpfApp1.Enum;
using WpfApp1.Model;

namespace WpfApp1.ViewModel
{
    class ScheduleViewModel
    {
        private List<ScheduleType> types = new List<ScheduleType>();
        public ObservableCollection<Schedule> schedules = new ObservableCollection<Schedule>();

        internal ObservableCollection<Schedule> Schedules { get => schedules; set => schedules = value; }

        public ScheduleViewModel()
        {
            InitDb();
            SetModel();
        }

        public static void InitDb()
        {
            string sql_init = "CREATE TABLE if not exists schedules(id INTEGER PRIMARY KEY AUTOINCREMENT, title nvarchar(255),time nvarchar(16),type INTEGER(2) ,pre_intervals INTEGER(3),created_at INTEGER)";
            SQLiteCommand command = new SQLiteCommand(sql_init, MainWindow.connection);
            command.ExecuteNonQuery();
        }

        private void SetModel()
        {
            string sql_select = "select * from schedules";
            SQLiteCommand command = new SQLiteCommand(sql_select, MainWindow.connection);
            SQLiteDataReader reader = command.ExecuteReader();
            string typeDesc = "";
            while (reader.Read())
            {
                typeDesc = ((ScheduleTypes)(long)reader["type"]).ToString();
                schedules.Add(new Schedule()
                {
                    Id = (long)reader["id"],
                    Title = reader["title"].ToString(),
                    Time = reader["time"].ToString(),
                    Type = (long)reader["type"],
                    Pre_intervals = (long)reader["pre_intervals"],
                    Type_desc = typeDesc,
                });
            }

            foreach (int index in System.Enum.GetValues(typeof(ScheduleTypes)))
            {
                types.Add(new ScheduleType()
                {
                    Tag = index,
                    Type = ((ScheduleTypes)index).ToString()
                });
            }
        }
    }
}
